package cn.itcast.n3_Java线程;

import lombok.extern.slf4j.Slf4j;

/**
 * @program: juc
 * @description:
 * @author: flyduck
 * @create: 2024-08-29 15:31
 **/
@Slf4j(topic = "c.Test19_$$$$$_interrupt设计模式_优雅停止线程_两阶段终止模式")
public class Test19_$$$$$_interrupt设计模式_优雅停止线程_两阶段终止模式 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination1 twoPhaseTermination1 = new TwoPhaseTermination1();
        twoPhaseTermination1.start();

        Thread.sleep(3500);

        twoPhaseTermination1.stop();
    }
}

@Slf4j(topic = "c.TwoPhaseTermination1")
class TwoPhaseTermination1{

    private Thread monitor;

    //启动监控线程
    public void start(){
        monitor = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                   log.debug("料理后事");
                   break;
                }
                try {
                    Thread.sleep(1000);//被打断的地方1
                    log.debug("执行监控记录");//被打断的地方2
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();//重新设置打断标记
                }
            }
        });
        monitor.start();
    }

    //停止监控线程
    public void stop(){
        monitor.interrupt();
    }

}
